package cn.sylinx.hbatis.ds;

import java.sql.Connection;
import java.sql.SQLException;

import javax.sql.DataSource;

import cn.sylinx.hbatis.db.dialect.DbType;
import cn.sylinx.hbatis.log.GLog;

/**
 * JDBC资源
 * 
 * @author han
 *
 */
public class JdbcResource implements Resource<Connection> {

	/**
	 * 数据源
	 */
	private DataSourceWrapper dataSourceWrapper;

	/**
	 * 数据源名称
	 */
	private String dataSourceName;

	/**
	 * 事务Connection缓存
	 */
	private final ThreadLocal<Connection> transactionConnections = new ThreadLocal<Connection>();

	/**
	 * 构造器
	 * 
	 * @param dataSourceName 数据源名称
	 * @param dataSource     数据源
	 */
	public JdbcResource(String dataSourceName, DataSourceWrapper dataSourceWrapper) {
		this.dataSourceWrapper = dataSourceWrapper;
		this.dataSourceName = dataSourceName;
	}

	/**
	 * 获取数据源
	 * 
	 * @return
	 */
	public DataSource getDataSource() {
		return dataSourceWrapper.getDataSource();
	}

	/**
	 * 获取数据源名称
	 * 
	 * @return
	 */
	public String getDataSourceName() {
		return dataSourceName;
	}

	/**
	 * 获取数据库类型
	 * 
	 * @return
	 */
	public DbType getDbType() {
		return dataSourceWrapper.getDbType();
	}

	/**
	 * 设置事务Connection缓存
	 * 
	 * @param connection Connection
	 */
	public final void setTransactionConnection(Connection connection) {
		transactionConnections.set(connection);
	}

	/**
	 * 获取当前线程的事务Connection
	 * 
	 * @return Connection
	 */
	public final Connection getTransactionConnection() {
		return transactionConnections.get();
	}

	/**
	 * 删除当前线程的事务Connection
	 */
	public final void removeTransactionConnection() {
		transactionConnections.remove();
	}

	@Override
	public Connection get() {

		Connection conn = transactionConnections.get();
		if (conn != null) {
			return conn;
		}

		try {
			return dataSourceWrapper.getDataSource().getConnection();
		} catch (SQLException e) {
			GLog.error("dataSource.getConnection() error: ", e);
		}

		return null;
	}

	@Override
	public void close(Connection resource) {

		if (transactionConnections.get() == null) {
			if (resource != null) {

				try {
					resource.close();
				} catch (SQLException e) {
					GLog.error("resource.close() error: ", e);
				}
			}
		}

	}

}
